package com.lyn.utils;

import android.text.TextUtils;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.regex.Pattern;

public class CheckFieldUtil {


    public static String check(Object object) {
        if (object == null) {
            return "请求参数不能为空";
        }
        Class<?> aClass = object.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            field.setAccessible(true);
            boolean annotationPresent = field.isAnnotationPresent(CheckField.class);
            if (annotationPresent) {
                CheckField checkField = field.getAnnotation(CheckField.class);
                try {
                    Object o = field.get(object);
                    if (!checkField.nullable()) {
                        if (o==null) {
                            return checkField.nullableMsg();
                        }
                    }
                    String string = (String) o;
                    int length = checkField.length();
                    if (length != -1) {
                        if (string.length() != length) {
                            return checkField.lengthMsg();
                        }
                    }
                    if (checkField.isPhone()) {
                        if (!TextUtils.isEmpty(string)) {
                            if (!checkPhone(string)) {
                                return checkField.isPhoneMsg();
                            }
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 正则：手机号（简单）, 1字头＋10位数字即可.
     *
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[1]\\d{10}$");
        return pattern.matcher(phone).matches();
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD})
    public @interface CheckField {
        boolean nullable() default true;

        String nullableMsg() default "";

        int length() default -1;

        String lengthMsg() default "";


        boolean isPhone() default false;

        String isPhoneMsg() default "手机号格式不正确";
    }
}
